package com.wcs.exam.dao.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.wcs.exam.common.base.page.SqlUtil;
import com.wcs.exam.dao.ExamUserRecordDao;
import com.wcs.exam.dao.impl.mapper.entity.ExamUserRecord;
import com.wcs.exam.dao.impl.mapper.ExamUserRecordMapper;
import com.wcs.exam.dao.po.ExamUserRecordExamCountPO;
import com.wcs.exam.dao.po.ExamUserRecordUserCountPO;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 考试用户记录 持久化实现类
 *
 * @author wcs
 * @since 2025-03-13
 */
@Repository
public class ExamUserRecordDaoImpl extends ServiceImpl<ExamUserRecordMapper, ExamUserRecord> implements ExamUserRecordDao {

    @Override
    public <R> List<R> selectObjs(Wrapper<ExamUserRecord> wrapper, Class<R> classType) {
        List<Map<String, Object>> resultMaps = baseMapper.selectMaps(wrapper);
        if (CollectionUtil.isEmpty(resultMaps)) {
            return Collections.emptyList();
        }
        return BeanUtil.copyToList(resultMaps, classType);
    }

    @Override
    public Integer getMaxSort() {
       return lambdaQuery().orderByDesc(ExamUserRecord::getSort).last(SqlUtil.limitOne()).oneOpt().map(ExamUserRecord::getSort).orElse(0);
    }

    @Override
    public List<ExamUserRecordUserCountPO> userCountByExamTypeAndRelateId(Integer examType, Long relateId, Collection<Long> userIds) {
        LambdaQueryWrapper<ExamUserRecord> wrapper = new QueryWrapper<ExamUserRecord>()
                .select("user_id as userId, count(1) as count")
                .lambda()
                .eq(ExamUserRecord::getExamType, examType)
                .eq(ExamUserRecord::getRelateId, relateId)
                .in(ExamUserRecord::getUserId, userIds);
        return selectObjs(wrapper, ExamUserRecordUserCountPO.class);
    }

    @Override
    public List<ExamUserRecordExamCountPO> examCountByUserIdAndRelateIds(Long userId, Collection<Long> relateIds) {
        LambdaQueryWrapper<ExamUserRecord> wrapper = new QueryWrapper<ExamUserRecord>()
                .select("exam_type as examType, relate_id as relateId, count(1) as count")
                .lambda()
                .eq(ExamUserRecord::getUserId, userId)
                .in(ExamUserRecord::getRelateId, relateIds)
                .groupBy(ExamUserRecord::getExamType, ExamUserRecord::getRelateId);
        return selectObjs(wrapper, ExamUserRecordExamCountPO.class);
    }
}
